/*
 *
 *   This file is part of jSevenBar. Copyright 2011 Alex Volodko
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */
package de.xhelp.jsevenbar.jni;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * Loader of the native library
 * 
 * @author Alex Volodko
 * 
 */
public class NativeLibLoader {
	private static final String LIB_NAME = "jsevenbar-";
	private static final String LIB_PATH_IN_JAR = "/lib/";
	static {
		loadFromLibraryPath(LIB_NAME+System.getProperty("os.arch"));
	}
	
	private static void loadFromLibraryPath(String libraryName) {
		try {
			System.loadLibrary(libraryName);
		} catch (UnsatisfiedLinkError e) {
			e.printStackTrace();
			loadFromJar(libraryName);
		}
	}

	/**
	 * If there native labrary was not found in java.library.path, this method
	 * will try to load it from the jar file.
	 */
	private static void loadFromJar(String libraryName) {
		long randomPart = new Date().getTime();
		File libFile = new File(System.getProperty("java.io.tmpdir") + "/"
				+ "JST_" + randomPart + LIB_PATH_IN_JAR + libraryName + ".dll");
		InputStream in = NativeLibLoader.class
				.getResourceAsStream(LIB_PATH_IN_JAR + libraryName + ".dll");
		try {
			if (libFile.getParentFile().mkdirs()) {
				FileOutputStream fw = new FileOutputStream(libFile);
				byte[] b = new byte[1024];
				int noOfBytes = 0;
				while ((noOfBytes = in.read(b)) != -1) {
					fw.write(b, 0, noOfBytes);
				}
				in.close();
				fw.close();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		System.load(libFile.toString());
	}
}
